#include "server.h"

int CreateTcpServer(int sin_port)
{
	int sock = socket(AF_INET,SOCK_STREAM,0);
	struct sockaddr_in saddr;
	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(sin_port);
	//inet_pton(AF_INET,"0.0.0.0",&saddr.sin_addr.s_addr);
	saddr.sin_addr.s_addr = INADDR_ANY;

	int opt = 1;
	setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
	if(bind(sock,(struct sockaddr *)&saddr,sizeof(saddr)))
	{
		perror("bind error\n");
		close(sock);
		return 0;
	}

	listen(sock,20);

	return sock;
}

void *down_upload_server(void *arg)
{
	pthread_detach(pthread_self());
	int sock = CreateTcpServer(8889);

	struct sockaddr_in caddr;
	unsigned int len = sizeof(caddr);
	int csock;
	pthread_t tid;
	
	while((csock = accept(sock,(struct sockaddr *)&caddr,&len)) >= 0)
	{
		int *p = (int *)malloc(sizeof(int));
		*p = csock;
		pthread_create(&tid,NULL,down_upload_file,p);		
	}
	return NULL;
}

void *down_upload_file(void *arg)
{
	pthread_detach(pthread_self());
	int csock = *(int *)arg;
	char buf[1024];
	char filebuf[1024];
	char filename[100];

	while(recv(csock,buf,sizeof(buf),0) > 0)
	{
		if(!strncmp(buf,"upload",6))
		{
			strcpy(filename,buf+7);
			int fd = open(filename,O_WRONLY | O_CREAT,0666);
			int file_l;
			recv(csock,&file_l,4,0);
			int len,l = 0;
			while((len = recv(csock,filebuf,sizeof(filebuf),0)) > 0)
			{
				write(fd,filebuf,len);
				memset(filebuf,0,sizeof(filebuf));
				l += len;
				if(l == file_l)
					break;
			}
			close(fd);
			printf("%s - upload success!\n",filename);
			close(csock);
			break;
		}
		else if(!strncmp(buf,"download",8))
		{
			strcpy(filename,buf+9);
			struct stat buf1;
			stat(filename,&buf1);
			send(csock,&buf1.st_size,4,0);
			int fd = open(filename,O_RDONLY);
			int ret;
			while((ret = read(fd,filebuf,1024)) > 0)
			{
				send(csock,filebuf,ret,0);
			}
			close(fd);
			printf("%s - download success!\n",filename);
			close(csock);
			break;

		}
	}

	return NULL;


}